<?php
namespace app\common\lib\redis;

class Predis
{
    //以单例模式访问redis
    private static $_instance = null;
    public $redis = '';
    private function __construct()
    {
        $this->redis = new \Redis();
        $response = $this->redis->connect(config('redis.host'),config('redis.port'),config('redis.timeOut'));
        if($response === false){
            throw new \Exception('redis connect error');
        }
    }
    public static function getInstance()
    {
        if(empty(self::$_instance)){
            return self::$_instance = new self();
        }
        return self::$_instance;
    }
    //添加键值对
    public function set($key,$value,$time = 0)
    {
        if(!$key){
            return  '';
        }
        if(is_array($value)){
            $value = json_encode($value);
        }
        if(!$time){
            return $this->redis->set($key,$value);
        }else{
            return $this->redis->setex($key,$time,$value);
        }
    }
    //获取键值对
//    public function get($key)
//    {
//        if(!$key){
//            return '';
//        }
//        return $this->redis->get($key);
//    }
//    //添加有序集合
//    public function sAdd($key,$value)
//    {
//        return $this->redis->sAdd($key,$value);
//    }
//    //获取有序集合中所有的值
//    public function sMembers($key)
//    {
//        return $this->redis->sMembers($key);
//    }
//    //删除有序集合中某个元素
//    public function sRem($key,$value)
//    {
//        return $this->redis->sRem($key,$value);
//    }
//    //删除key
//    public function del($key)
//    {
//        return $this->redis->del($key);
//    }

    public function __call($name,$arguments)
    {
        if(count($arguments)>1){
            return $this->redis->$name($arguments[0],$arguments[1]);
        }else{
            return $this->redis->$name($arguments[0]);
        }
    }
}